package com.onlinemarket.thrid.daoimpl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.onlinemarket.thrid.dao.warehouseDao;
import com.onlinemarket.thrid.domain.WareHouse;

@Repository
public class warehouseDaoImpl implements warehouseDao {
	@Autowired
	private JdbcTemplate jdbcTemplate;
	private WareHouse wareHouse;

	@Override
	public int addwarehouse(WareHouse wareHouse) {
		String sql = "insert into warhouse (warehouse_name,warehouse_adderss) values(?,?)";
		int insertnumber = jdbcTemplate.update(sql,
				new Object[] { wareHouse.getWarehouse_name(), wareHouse.getWarehouse_address() });
		return insertnumber;
	}

	@Override
	public boolean deletewarehouse(int warehouse_id) {
		String sql = "delete from warehouse where warehouse_id=?";
		int deletenumber = jdbcTemplate.update(sql, new Object[] { warehouse_id });
		return deletenumber == 1 ? true : false;
	}

	@Override
	public List<WareHouse> getAllwarehouse() {
		List<WareHouse> list = new ArrayList<WareHouse>();
		String sql = "SELECT * FROM warehouse;";
		List<Map<String, Object>> listofqwarehouse = jdbcTemplate.queryForList(sql);
		Iterator<Map<String, Object>> iterator = listofqwarehouse.iterator();
		while (iterator.hasNext()) {
			Map<String, Object> map = iterator.next();
			WareHouse wareHouse = new WareHouse();
			wareHouse.setWarehouse_id(Integer.parseInt(map.get("warehouse_id").toString()));
			wareHouse.setWarehouse_name(map.get("warehouse_name").toString());
			wareHouse.setWarehouse_address(map.get("warehouse_address").toString());
			list.add(wareHouse);
		}
		return list;
	}

	public WareHouse getwarehouseById(Integer warehouseid) {
		String sql = "select * from warehouse where warehouse_id=?;";
		List<Map<String, Object>> warehouses = jdbcTemplate.queryForList(sql, new Object[] { warehouseid });
		Iterator<Map<String, Object>> iterator = warehouses.iterator();
		while (iterator.hasNext()) {
			Map<String, Object> map = iterator.next();
			wareHouse = new WareHouse(Integer.parseInt(map.get("warehouse_id").toString()),
					map.get("warehouse_name").toString(), map.get("warehouse_address").toString());
		}
		return wareHouse;
	}

	@Override
	public boolean updateinfo(int id,String name,String add) {
		String sql = " UPDATE warehouse set warehouse_name=?,warehouse_address=? where warehouse_id =?";
		int updatenumber = jdbcTemplate.update(sql, new Object[] {name,add,id} );
		return updatenumber == 1 ? true : false;
	};

}
